<script setup lang="ts">
defineOptions({
  name: "add"
});

import { ref, reactive, computed, onMounted } from "vue";
import type { FormInstance, FormRules } from "px-ui";
import { createGasWaste, updateGasWaste, queryGasWasteDetail } from "@/api/modules/operation";
import { useRouterStoreHook } from "@/store/modules/router";
import { useThrottleFn } from "@vueuse/core";
import { throttleDelay as delay } from "@/utils/constant";

interface Props {
  // 弹框类型 add 新增   edit 编辑
  type: "add" | "edit";
  id: string;
}

const props = withDefaults(defineProps<Props>(), {});
const dialogTableVisible = defineModel({ type: Boolean, default: false });
const title = computed(() => (props.type === "add" ? "新增" : "编辑"));
const loading = ref(false);

const wasteTypeOptions = [
  {
    label: "C级防护服",
    value: "C_CLOTHES"
  },
  {
    label: "D级防护服",
    value: "D_CLOTHES"
  },
  {
    label: "废液桶",
    value: "WASTE_TANK"
  },
  {
    label: "空桶",
    value: "NULL_TANK"
  },
  {
    label: "手套",
    value: "GLOVE"
  },
  {
    label: "吸酸棉",
    value: "ACID_ABSORBING_COTTON"
  },
  {
    label: "纸带",
    value: "PAPER_TAPE"
  }
];

const dangerousNatureOptions = [
  {
    label: "酸性",
    value: "ACIDITY"
  },
  {
    label: "碱性",
    value: "ALKALINE"
  },
  {
    label: "易燃",
    value: "COMBUSTIBLE"
  }
];

const wasteProductionProcessOptions = [
  {
    label: "换桶",
    value: "换桶"
  },
  {
    label: "取样",
    value: "取样"
  },
  {
    label: "换纸带",
    value: "换纸带"
  }
];

interface RuleForm {
  wasteType: string;
  dangerousNature: string;
  wasteProductionProcess: string;
  productionDay: string;
  productionTime: string;
  wasteNum: number;
  wasteMaterialVolume: number;
  wasteWeight: number;
  transferDay: string;
  transferTime: string;
  wasteDestination: string;
  productionDepartmentSign: string;
  transferDepartmentSign: string;
}

const formSize = ref("default");
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
  wasteType: "",
  dangerousNature: "",
  wasteProductionProcess: "",
  productionDay: "",
  productionTime: "",
  wasteNum: undefined,
  wasteMaterialVolume: undefined,
  wasteWeight: undefined,
  transferDay: "",
  transferTime: "",
  wasteDestination: "",
  productionDepartmentSign: "",
  transferDepartmentSign: ""
});

const rules = reactive<FormRules<RuleForm>>({
  wasteType: [{ required: true, message: "请选择废弃物类别", trigger: "blur" }],
  dangerousNature: [{ required: true, message: "请选择危险特性", trigger: "blur" }],
  wasteProductionProcess: [{ required: true, message: "请选择产废环节", trigger: "blur" }],
  productionDay: [{ required: true, message: "请选择产生日期", trigger: "blur" }],
  productionTime: [{ required: true, message: "请选择产生时间", trigger: "blur" }],
  wasteNum: [{ required: true, message: "请输入废物数量", trigger: "blur" }],
  wasteMaterialVolume: [{ required: true, message: "请输入盛废材料及容积", trigger: "blur" }],
  wasteWeight: [{ required: true, message: "请输入废物重量", trigger: "blur" }],
  transferDay: [{ required: true, message: "请选择转移日期", trigger: "blur" }],
  transferTime: [{ required: true, message: "请选择转移时间", trigger: "blur" }],
  wasteDestination: [{ required: true, message: "请输入废物去向", trigger: "blur" }],
  productionDepartmentSign: [{ required: false, message: "请输入产废部门签字", trigger: "blur" }],
  transferDepartmentSign: [{ required: false, message: "请输入转运部门签字", trigger: "blur" }]
});

const emits = defineEmits(["submit"]);

const wasteProductionProcessBlurHandler = (e: any) => {
  if (e.target.value) {
    ruleForm.wasteProductionProcess = e.target.value;
  }
};

const cancelHandler = () => {
  dialogTableVisible.value = false;
};

const submitHandler = useThrottleFn(async () => {
  if (!ruleFormRef.value) return;
  await ruleFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      loading.value = true;
      const { id } = props;
      const params = { ...ruleForm };
      if (props.type === "add") {
        await createGasWaste(params, () => {
          loading.value = false;
        });
      } else if (props.type === "edit") {
        params["id"] = id;
        await updateGasWaste(params, () => {
          loading.value = false;
        });
      }
      loading.value = false;
      emits("submit");
      dialogTableVisible.value = false;
    } else {
      console.error("error submit!", fields);
    }
  });
}, delay);

const init = async () => {
  loading.value = true;
  if (props.type === "edit") {
    const { id } = props;
    const res = await queryGasWasteDetail(id, () => {
      loading.value = false;
    });
    const {
      wasteType = "",
      dangerousNature = "",
      wasteProductionProcess = "",
      productionDay = "",
      productionTime = "",
      wasteNum = "",
      wasteMaterialVolume = "",
      wasteWeight = "",
      transferDay = "",
      transferTime = "",
      wasteDestination = "",
      productionDepartmentSign = "",
      transferDepartmentSign = ""
    } = res;
    ruleForm.wasteType = wasteType;
    ruleForm.dangerousNature = dangerousNature;
    ruleForm.wasteProductionProcess = wasteProductionProcess;
    ruleForm.productionDay = productionDay;
    ruleForm.productionTime = productionTime;
    ruleForm.wasteNum = wasteNum;
    ruleForm.wasteMaterialVolume = wasteMaterialVolume;
    ruleForm.wasteWeight = wasteWeight;
    ruleForm.transferDay = transferDay;
    ruleForm.transferTime = transferTime;
    ruleForm.wasteDestination = wasteDestination;
    ruleForm.productionDepartmentSign = productionDepartmentSign;
    ruleForm.transferDepartmentSign = transferDepartmentSign;
  }
  loading.value = false;
};

onMounted(async () => {
  await init();
});
</script>

<template>
  <px-dialog v-model="dialogTableVisible" :title="title" width="1000px">
    <px-form
      ref="ruleFormRef"
      v-loading="loading"
      :model="ruleForm"
      :rules="rules"
      inline
      label-width="130px"
      class="demo-ruleForm"
      :size="formSize"
      status-icon
    >
      <px-row :gutter="32">
        <px-col :span="12">
          <px-form-item label="废弃物类别" prop="wasteType">
            <px-select v-model="ruleForm.wasteType" clearable filterable placeholder="请选择废弃物类别">
              <px-option v-for="item in wasteTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
            </px-select>
          </px-form-item>
        </px-col>
        <px-col :span="12">
          <px-form-item label="危险特性" prop="dangerousNature">
            <px-select v-model="ruleForm.dangerousNature" clearable filterable placeholder="请选择危险特性">
              <px-option v-for="item in dangerousNatureOptions" :key="item.value" :label="item.label" :value="item.value" />
            </px-select>
          </px-form-item>
        </px-col>
        <px-col :span="12">
          <px-form-item label="产废环节" prop="wasteProductionProcess">
            <px-select
              v-model="ruleForm.wasteProductionProcess"
              clearable
              filterable
              allow-create
              placeholder="请选择产废环节"
              @blur="wasteProductionProcessBlurHandler"
            >
              <px-option v-for="item in wasteProductionProcessOptions" :key="item.value" :label="item.label" :value="item.value" />
            </px-select>
          </px-form-item>
        </px-col>
        <px-col :span="12">
          <px-form-item label="产生日期" prop="productionDay">
            <px-date-picker
              v-model="ruleForm.productionDay"
              clearable
              type="date"
              :editable="false"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              :default-time="new Date(2000, 1, 1)"
              placeholder="请选择产生日期"
            />
          </px-form-item>
        </px-col>
        <px-col :span="12">
          <px-form-item label="产生时间" prop="productionTime">
            <px-time-picker v-model="ruleForm.productionTime" format="HH:mm:ss" value-format="HH:mm:ss" clearable placeholder="请选择产生时间" />
          </px-form-item>
        </px-col>
        <px-col :span="12">
          <px-form-item label="废物数量" prop="wasteNum">
            <px-input
              v-model.trim.number="ruleForm.wasteNum"
              class="px-input-number-no-controls"
              type="number"
              clearable
              :min="0"
              placeholder="请输入废物数量"
            />
          </px-form-item>
        </px-col>
        <px-col :span="12">
          <px-form-item label="盛废材料及容积" prop="wasteMaterialVolume">
            <px-input
              v-model.trim.number="ruleForm.wasteMaterialVolume"
              class="px-input-number-no-controls"
              type="number"
              clearable
              :min="0"
              placeholder="请输入盛废材料及容积"
            />
          </px-form-item>
        </px-col>
        <px-col :span="12">
          <px-form-item label="废物重量（KG）" prop="wasteWeight">
            <px-input
              v-model.trim.number="ruleForm.wasteWeight"
              class="px-input-number-no-controls"
              type="number"
              clearable
              :min="0"
              placeholder="请输入废物重量"
            />
          </px-form-item>
        </px-col>
        <px-col :span="12">
          <px-form-item label="转移日期" prop="transferDay">
            <px-date-picker
              v-model="ruleForm.transferDay"
              clearable
              type="date"
              :editable="false"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              :default-time="new Date(2000, 1, 1)"
              placeholder="请选择转移日期"
            />
          </px-form-item>
        </px-col>
        <px-col :span="12">
          <px-form-item label="转移时间" prop="transferTime">
            <px-time-picker v-model="ruleForm.transferTime" format="HH:mm:ss" value-format="HH:mm:ss" clearable placeholder="请选择转移时间" />
          </px-form-item>
        </px-col>
        <px-col :span="12">
          <px-form-item label="废物去向" prop="wasteDestination">
            <px-input v-model.trim="ruleForm.wasteDestination" clearable placeholder="请输入废物去向" />
          </px-form-item>
        </px-col>
        <px-col :span="12">
          <px-form-item label="产废部门签字" prop="productionDepartmentSign">
            <px-input v-model.trim="ruleForm.productionDepartmentSign" clearable placeholder="请输入产废部门签字" />
          </px-form-item>
        </px-col>
        <px-col :span="12">
          <px-form-item label="转运部门签字" prop="transferDepartmentSign">
            <px-input v-model.trim="ruleForm.transferDepartmentSign" clearable placeholder="请输入转运部门签字" />
          </px-form-item>
        </px-col>
      </px-row>
    </px-form>

    <template #footer>
      <span class="dialog-footer">
        <px-button @click="cancelHandler">取消</px-button>
        <px-button type="primary" :loading="loading" @click="submitHandler"> 确认 </px-button>
      </span>
    </template>
  </px-dialog>
</template>

<style lang="scss" scoped>
:deep(.px-form-item) {
  width: 100%;

  .px-form-item__content {
    .px-input-number .px-input__inner {
      text-align: left;
    }

    .px-input,
    .px-input-number,
    .px-select,
    .px-date-picker,
    .px-time-picker,
    .px-tree-select {
      width: 100%;
    }
  }
}
</style>
